import axios from 'axios'
import { getToken } from '@/utils/token'
import router from '@/router'
import { Message, Loading } from 'element-ui'
let loadingInstance = null
const request = axios.create({
  baseURL: '/api',
  timeout: 6000
})
// 定义拦截器
request.interceptors.request.use(function (config) {
  loadingInstance = Loading.service({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  const token = getToken()
  if (config.url !== 'https://geo.datav.aliyun.com/areas_v3/bound/340100_full.json') {
    if (token) {
      config.headers.token = token
    }
  }
  return config
}, function (error) {
  loadingInstance.close()
  return Promise.reject(error)
})

request.interceptors.response.use(function (response) {
  loadingInstance.close()
  switch (response.data.code) {
    case 401:
      Message({
        type: 'error',
        message: '登录信息过期',
        duration: 1000,
        onClose: () => {
          router.replace('/login')
        }
      })
      break
    case 403:
      Message({
        type: 'error',
        message: '用户未登录',
        duration: 1000,
        onClose: () => {
          router.replace('/login')
        }
      })
      break
    default:
      break
  }
  return response
}, function (error) {
  loadingInstance.close()
  return Promise.reject(error)
})

export default request
